<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: mslaria $ ($Date: 2007/04/18 07:31:34 $)
// $RCSfile: functions_subscribers.php,v $ : $Revision: 1.7 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================


if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

/**
* Insert a new subscriber
*/
function insertSubscriber($email, $validated = false, $userid = 0, $tgroupid = 0)
{
	global $dbCore, $_SWIFT, $template;

	$_subscriber = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."newssubscribers` WHERE `email` = '". $dbCore->escape($email) ."';");
	if (!empty($_subscriber["email"]))
	{
		return false;
	}

	$dbCore->query("INSERT INTO `". TABLE_PREFIX ."newssubscribers` (`tgroupid`, `userid`, `email`, `dateline`, `validated`) VALUES ('". intval($tgroupid) ."', '". intval($userid) ."', '". $dbCore->escape($email) ."', '". DATENOW ."', '". iif($validated==true, "1", "0") ."');");
	$newssubscriberid = $dbCore->lastInsertId();
	if (!$newssubscriberid)
	{
		return false;
	}

	if (!$validated)
	{
		$validatehash = buildHash();
		$dbCore->shutdownQuery("INSERT INTO `". TABLE_PREFIX ."newsverihash` (`newsverihashid`, `newssubscriberid`, `hash`, `dateline`) VALUES ('". $dbCore->escape($validatehash) ."', '". intval($newssubscriberid) ."', '". $dbCore->escape($validatehash) ."', '". DATENOW ."');");
		// Send Validation Email
		if(!empty($tgroupid)){
			$template->setGroup($tgroupid);
		}else
		{
			$template->setGroup("1");
		}
		$template->assign("hash", $validatehash);
		$template->loadLanguageSection("newsclient", TEMPLATE_DB);

		$template->assign("ishtml", true);
		$_templateresulthtml = $template->displayTemplate("email_newssubscribervalidate", TEMPLATE_DB);
		$template->assign("ishtml", false);
		$_templateresulttext = $template->displayTemplate("email_newssubscribervalidate", TEMPLATE_DB);
		require_once ("./includes/functions_mail.php");
		$mailObj = new SWIFT_Mail();

		$mailObj->setSubject(sprintf($_SWIFT["language"]["nwvalidatesubscriptionsub"], $_SWIFT["settings"]["general_companyname"]));
		$mailObj->setData($_templateresulthtml, $_templateresulttext);

		$mailObj->sendMail(array($email), $_SWIFT["settings"]["general_returnemail"], $_SWIFT["settings"]["general_companyname"], false);
	} else {
		sendSubscriberConfirmationMail($tgroupid, $email);
	}

	return true;
}

/**
* Send the confirmation mail
*/
function sendSubscriberConfirmationMail($tgroupid, $email)
{
	global $_SWIFT, $template;

	// Send Confirmation Email
	if(!empty($tgroupid)){
		$template->setGroup($tgroupid);
	}else
	{
		$template->setGroup("1");
	}
	$template->assign("email", $email);
	$template->loadLanguageSection("newsclient", TEMPLATE_DB);

	$template->assign("ishtml", true);
	$_templateresulthtml = $template->displayTemplate("email_newssubscriberconfirm", TEMPLATE_DB);
	$template->assign("ishtml", false);
	$_templateresulttext = $template->displayTemplate("email_newssubscriberconfirm", TEMPLATE_DB);
	require_once ("./includes/functions_mail.php");
	$mailObj = new SWIFT_Mail();

	$mailObj->setSubject(sprintf($_SWIFT["language"]["nwsubconfirmsub"], $_SWIFT["settings"]["general_companyname"]));
	$mailObj->setData($_templateresulthtml, $_templateresulttext);

	$mailObj->sendMail(array($email), $_SWIFT["settings"]["general_returnemail"], $_SWIFT["settings"]["general_companyname"], false);
}

/**
* Delete the given news subscribers
*/
function deleteSubscribers($newssubscriberidlist)
{
	global $dbCore;

	if (!_is_array($newssubscriberidlist))
	{
		return false;
	}

	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."newssubscribers` WHERE `newssubscriberid` IN (". buildIN($newssubscriberidlist) .");");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."newsverihash` WHERE `newssubscriberid` IN (". buildIN($newssubscriberidlist) .");");

	return true;
}

/**
* Update the subscribers email address
*/
function updateSubscriber($newssubscriberid, $email)
{
	global $dbCore;

	$dbCore->query("UPDATE `". TABLE_PREFIX ."newssubscribers` SET email = '". $dbCore->escape($email) ."' WHERE `newssubscriberid` = '". intval($newssubscriberid) ."';");
}

/**
* Validate a non validated subscriber
*/
function validateSubscriber($newssubscriberid)
{
	global $dbCore;

	$_subscriber = $dbCore->queryFetch("SELECT * FROM `". TABLE_PREFIX ."newssubscribers` WHERE `newssubscriberid` = '". intval($newssubscriberid) ."';");
	if (empty($_subscriber["newssubscriberid"]))
	{
		return false;
	}

	$dbCore->query("UPDATE `". TABLE_PREFIX ."newssubscribers` SET `validated` = '1' WHERE `newssubscriberid` = '". intval($newssubscriberid) ."';");
	$dbCore->query("DELETE FROM `". TABLE_PREFIX ."newsverihash` WHERE `newssubscriberid` = '". intval($newssubscriberid) ."';");

	sendSubscriberConfirmationMail($_subscriber["tgroupid"], $_subscriber["email"]);

	return true;
}

/**
* Exports all existing subscribers
*/
function exportSubscribers($filename = "")
{
	global $dbCore;

	$dbCore->query("SELECT * FROM `". TABLE_PREFIX ."newssubscribers` WHERE `validated` = '1' ORDER BY `newssubscriberid` ASC;");
	while ($dbCore->nextRecord())
	{
		$subscriberdata .= $dbCore->Record["email"].SWIFT_CRLF;
	}

	headerNoCache();
	header("Content-Type: application/octet-stream".SWIFT_CRLF);
	header("Content-Length: ". strlen($subscriberdata) ."\n");
	header("Content-Transfer-Encoding: binary\n");

	if (empty($filename))
	{
		$filename = "subscribers.csv";		
	}

	if (strpos($_SERVER['HTTP_USER_AGENT'], "MSIE")){
		header("Content-Disposition: ; filename=\"". $filename ."\"");
	} else{
		header("Content-Disposition: attachment; filename=\"". $filename ."\"");
	}

	echo $subscriberdata;

	return true;
}

/**
* Import subscribers
*/
function importSubscribers($subscriberdata)
{
	global $dbCore;

	$subscriberdata = preg_replace("#(\r\n|\r|\n)#s", "\n", $subscriberdata); // Convert any \r\n's to \n
	$subscriberarray = explode("\n", $subscriberdata);

	$successemails = $failedemails = $totalemails = 0;
	$emaillist = "";
	$result = $_finalmaillist = array();

	$totalemails = count($subscriberarray);

	$dbCore->query("SELECT `email` FROM `". TABLE_PREFIX ."newssubscribers` WHERE `email` IN (". buildIN($subscriberarray) .");");
	while ($dbCore->nextRecord())
	{
		$_finalmaillist[] = $dbCore->Record["email"];
	}

	if ($totalemails)
	{
		$insertsql = array();
		foreach ($subscriberarray as $key=>$val)
		{
			if (trim($val) != "")
			{
				if (isValidEmail($val) && !in_array($val, $_finalmaillist))
				{
					$insertsql[] = "('0', '0', '". $dbCore->escape($val) ."', '". DATENOW ."', '1')";
					$successemails++;
				} else {
					$failedemails++;
					$emaillist .= $val.SWIFT_CRLF;
				}
			}
		}

		if (count($insertsql))
		{
			$dbCore->query("INSERT INTO `". TABLE_PREFIX ."newssubscribers` (`tgroupid`, `userid`, `email`, `dateline`, `validated`) VALUES ". implode(",", $insertsql) .";");
		}
	}

	$result["successemails"] = $successemails;
	$result["failedemails"] = $failedemails;
	$result["totalemails"] = $totalemails;
	$result["emaillist"] = $emaillist;

	return $result;
}
?>